﻿using GalaSoft.MvvmLight;
using HtmlAgilityPack;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SharpDesktoptool.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            ////if (IsInDesignMode)
            ////{
            ////    // Code runs in Blend --> create design time data.
            ////}
            ////else
            ////{
            ////    // Code runs "for real"
            ////}
            ///
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        // From Web
                        var url = "http://www.tianqi.com/binjianqu/";
                        var web = new HtmlWeb();
                        web.OverrideEncoding = Encoding.UTF8;
                        var doc = web.Load(url);
                        var showtext = string.Empty;
                        var selectnode = doc.DocumentNode.SelectSingleNode(".//dd[@class='weather']");

                        WeatherImage = "http:"+selectnode.SelectSingleNode("i/img").Attributes["src"].Value;

                        showtext += selectnode.SelectSingleNode("p/b").InnerText + selectnode.SelectSingleNode("p/i").InnerText + " ";
                        showtext += selectnode.SelectSingleNode("span").InnerText.Replace("<b>", string.Empty).Replace("</b>", string.Empty);

                        WeatherInfo = showtext;
                        Thread.Sleep(60000);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            });

            var timer = new System.Timers.Timer(5000);
            timer.Elapsed += (s, e) =>
            {
                WeatherTime = "🕑 " + DateTime.Now.ToString("HH:mm");
            };
            timer.Start();
        }

        private string _weatherImage;
        private string _weatherInfo;
        private string _weatherTime = string.Empty;

        public string WeatherImage { get => _weatherImage; set => Set(ref _weatherImage, value); }
        public string WeatherInfo { get => _weatherInfo; set => Set(ref _weatherInfo, value); }
        public string WeatherTime
        {
            get => _weatherTime; set => Set(ref _weatherTime, value);
        }
    }
}